/*
 * @Description:
 * @User: Vijay <1937832819@qq.com>
 * @Date: 2020-10-20 22:34:11
 */
package admin

import (
	"blogApi/commons"
	"blogApi/controllers"
	"blogApi/models"
	"encoding/json"
	"strings"
	"time"

	"github.com/dgrijalva/jwt-go"
)

// AdminController 控制器
type AdminController struct {
	controllers.BaseController
}

// InputData 参数接收器
type InputData struct {
	Username string
	Password string
}

// Login 用户登录
func (a *AdminController) Login() {
	if a.Ctx.Input.IsPost() == false {
		a.ResJson(1, "操作失败", "请求方式失败", nil)
	}
	var input InputData
	// 获取字符串形式的参数，用于ajax
	username := a.GetString("username")
	password := a.GetString("password")
	if username == "" && password == "" {
		// 获取 axios 传递的参数
		data := a.Ctx.Input.RequestBody
		err := json.Unmarshal(data, &input)
		if err != nil {
			a.ResJson(1, "存入失败", err.Error(), nil)
		}
		username = input.Username
		password = input.Password
	}
	if username == "" || password == "" {
		a.ResJson(1, "获取失败", "账号或密码为空", nil)
	}
	var admin models.Admin
	var db = models.Db
	db.Where("status = ?", "1").Where(
		db.Where("account=?", username).Or("tel=?", username),
	).First(&admin)
	if admin.Account == "" {
		a.ResJson(1, "获取失败", "账号密码错误", nil)
	}
	// 验证密码
	if admin.Password != a.Encode(password) {
		a.ResJson(1, nil, "密码错误", nil)
	}
	// 带权限创建令牌
	claims := make(jwt.MapClaims)
	claims["account"] = admin.Account
	claims["username"] = admin.Username
	claims["tel"] = admin.Tel
	claims["email"] = admin.Email
	claims["exp"] = time.Now().Add(time.Hour * 2).Unix() //2小时有效期，过期需要重新登录获取token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// 使用自定义字符串加密
	tokenString, err := token.SignedString([]byte("mykey"))
	if err != nil {
		a.ResJson(1, "加密失败", nil, nil)
	}
	// 返回数据
	jsonData := make(map[string]interface{}, 4)
	jsonData["token"] = tokenString
	jsonData["id"] = admin.Id
	jsonData["account"] = admin.Account
	jsonData["username"] = admin.Username
	jsonData["tel"] = admin.Tel
	jsonData["email"] = admin.Email
	a.ResJson(0, "获取成功", jsonData, nil)
}

// Logout 退出
func (a *AdminController) Logout() {
	if a.Ctx.Input.IsPost() == false {
		a.ResJson(1, "操作失败", "请求方式失败", nil)
	}
	// 获取token
	authString := a.Ctx.Input.Header("Authorization")
	kv := strings.Split(authString, " ")
	if len(kv) != 2 || kv[0] != "Bearer" {
		a.ResJson(0, "AuthString无效", nil, nil)
	}
	tokenString := kv[1]
	// token加入黑名单
	helper := commons.Helper{}
	cache, err := helper.NewRedisClient()
	if err != nil {
		a.ResJson(0, "缓存redis开启失败", nil, nil)
	}
	cache.Set(tokenString, 1, time.Hour*1).Err()
	a.ResJson(0, "退出成功", tokenString, nil)
}
